#include "syslog.h"
#include "w25q16.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static uint32_t current_address = LOG_FLASH_ADDR;


void log_init(void) {
    // 读取保存的当前地址
    W25Q16_ReadData(LOG_FLASH_FLAG_ADDR, (uint8_t *)&current_address, 4);
    
    printf("Current log address: 0x%08X (%u)\n", current_address, current_address);
    
    // 检查地址是否有效
    if(current_address < LOG_FLASH_ADDR || current_address >= LOG_FLASH_END) {
        printf("Invalid log address, resetting...\n");
        current_address = LOG_FLASH_ADDR; 
        
        // 擦除日志区域
        for(uint32_t addr = LOG_FLASH_ADDR; addr < LOG_FLASH_END; addr += 4*1024) {
            W25Q16_EraseSector(addr);
            
        }
        
        // 更新标志地址
        SPI_FLASH_BufferWrite((uint8_t *)&current_address, LOG_FLASH_FLAG_ADDR, 4);
        
    }
}


int add_log(const uint8_t *plog, uint32_t llen) {
    // 参数检查
    if(plog == NULL || llen == 0) {
        return -1;
    }
    
    // 空间检查
    if(current_address + llen > LOG_FLASH_END) {
        return -2; // 空间不足
    }
    
    // 写入日志数据
    SPI_FLASH_BufferWrite((uint8_t *)plog, current_address, llen);
    
    
    // 验证写入
    uint8_t *verify_buf = (uint8_t *)malloc(llen);
    if(verify_buf) {
        W25Q16_ReadData(current_address, verify_buf, llen);
        printf("verify_buf %s current_address %d\n", verify_buf, current_address);
        
        if(memcmp(plog, verify_buf, llen) != 0) {
            free(verify_buf);
            return -3; // 写入验证失败
        }
        free(verify_buf);
    }
    
    // 更新当前地址
    current_address += llen;
    
    // 更新标志地址
    W25Q16_EraseSector(LOG_FLASH_FLAG_ADDR);
    
    SPI_FLASH_BufferWrite((uint8_t *)&current_address, LOG_FLASH_FLAG_ADDR, 4);
    
    
    return 0;
}

void erase_logs()
{
    current_address = LOG_FLASH_ADDR;
    W25Q16_EraseSector(LOG_FLASH_ADDR);
}

void read_logs(uint8_t *plog, uint32_t llen)
{
    W25Q16_ReadData(LOG_FLASH_ADDR, plog, llen);
}
